package etcd

import (
	"context"
	"fmt"
	"grpc-test/config"
	"log"

	"go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/client/v3/naming/endpoints"
)

// 租约时间
const ttl = 10

var etcdClient *clientv3.Client

func init() {
	var err error
	etcdClient, err = clientv3.New(clientv3.Config{
		Endpoints: []string{config.EtcdUrl},
	})
	if err != nil {
		panic(err)
	}
}

func Register(addr string) error {
	
	log.Println("etcd regist server address :", addr)

	manager, err := endpoints.NewManager(etcdClient, config.ServiceName)
	if err != nil {
		return err
	}

	// 设置客户端的租期
	lease, err := etcdClient.Grant(context.TODO(), ttl)
	if err != nil {
		return err
	}

	err = manager.AddEndpoint(
		context.TODO(),
		fmt.Sprintf("%s/%s", config.ServiceName, addr),
		endpoints.Endpoint{Addr: addr},
		clientv3.WithLease(lease.ID),
	)
	if err != nil {
		return err
	}

	alive, err := etcdClient.KeepAlive(context.TODO(), lease.ID)
	if err != nil {
		return err
	}

	go func() {
		for {
			<-alive
			fmt.Println("etcd server keep alive")
		}
	}()

	return nil
}

func UnRegister(addr string) error {

	log.Println("etcd unregist server address :", addr)

	if etcdClient != nil {
		manager, err := endpoints.NewManager(etcdClient, config.ServiceName)
		if err != nil {
			return err
		}
		
		err = manager.DeleteEndpoint(context.TODO(), fmt.Sprintf("%s/%s", config.ServiceName, addr))
		if err != nil {
			return err
		}
		return err
	}

	return nil
}


func Stop() {
	etcdClient.Close()
}